package minh.bac.wcbrazil2014.shareface;

import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.Session.StatusCallback;
import com.facebook.model.GraphUser;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.WebDialog;
import com.facebook.widget.FacebookDialog.PendingCall;
import com.facebook.widget.WebDialog.OnCompleteListener;
import minh.bac.wcbrazil2014.R;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class ShareFaceFm extends Fragment{
	
	private UiLifecycleHelper uiFaceLifecycleHelper;
	
	FragmentManager fragmentManager;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View rootView = inflater.inflate(R.layout.facebook_fragment, container, false);
		//final String share = data.getTitle() + data.getContent().substring(0, 140) + "via Viet Foodie";
	//	TextView idF = new  TextView(getActivity());
		//idF.setText(Html.fromHtml(share));
	//	final String faceShare = idF.getText().toString();
		fragmentManager = getActivity().getSupportFragmentManager();
		Session.openActiveSession(getActivity(),ShareFaceFm.this, true, new Session.StatusCallback() {

		      // callback when session changes state
		      @Override
		      public void call(Session session, SessionState state, Exception exception) {
		        if (session.isOpened()) {

		          // make request to the /me API
		          Request.newMeRequest(session, new Request.GraphUserCallback() {

		            // callback after Graph API response with user object	            

					@Override
					public void onCompleted(GraphUser user, Response response) {
						// TODO Auto-generated method stub
						 if (user != null) {
				                //ShareFaceDialog("via Viet Foodie", data.getTitle(), faceShare, "", "");
				                publishFeedDialog("WOLD CUP Brazil 2014", "WC2014", "Have some fun", "https://play.google.com/store/apps/details?id=minh.bac.wcbrazil2014", "https://4c72c815f7b37207c6c82964db49e61643ba3cb6.googledrive.com/host/0B7NswZYEFBwmZ25jd1otWFF1bms/");
				              }
					}
		          }).executeAsync();
		        }
		      }
		    });
			//
			uiFaceLifecycleHelper = new UiLifecycleHelper(getActivity(), callback);
			uiFaceLifecycleHelper.onCreate(savedInstanceState);
		return rootView;
	}
	public void ShareFaceDialog(String name, String caption ,String description, String pictureLink, String link)
	{
		
		if (FacebookDialog.canPresentShareDialog(getActivity().getApplicationContext(), 
                FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
			// Publish the post using the Share Dialog
			FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(getActivity())
			.setLink(link)
			.build();
			uiFaceLifecycleHelper.trackPendingDialogCall(shareDialog.present());

		} else {
			// Fallback. For example, publish the post using the Feed Dialog
			publishFeedDialog(name, caption, description, pictureLink, link);
		}
	}
	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
	    if (state.isOpened()) {
	        Log.i("FaceBookDT", "Logged in...");
	    } else if (state.isClosed()) {
	        Log.i("FaceBookDT", "Logged out...");
	    }
	}
	private Session.StatusCallback callback = new StatusCallback() {
		
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			// TODO Auto-generated method stub
			onSessionStateChange(session, state, exception);
			
		}
	};
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
		uiFaceLifecycleHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
			
			@Override
			public void onError(PendingCall pendingCall, Exception error, Bundle data) {
				// TODO Auto-generated method stub
				Log.e("Activity", String.format("Error: %s", error.toString()));
			}
			
			@Override
			public void onComplete(PendingCall pendingCall, Bundle data) {
				// TODO Auto-generated method stub
				Log.i("Activity", "Success!");
			}
		});
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		
		super.onResume();
		uiFaceLifecycleHelper.onResume();
	}
	@Override
	public void onPause() {
		// TODO Auto-generated method stub		
		super.onPause();
		//menuFlag = false;
		uiFaceLifecycleHelper.onPause();
	}
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub		
		super.onDestroy();
		uiFaceLifecycleHelper.onDestroy();
	}@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub		
		super.onSaveInstanceState(outState);
		uiFaceLifecycleHelper.onSaveInstanceState(outState);
	}
	private void publishFeedDialog( String name, String caption ,String description, String pictureLink, String link ) {
	    Bundle params = new Bundle();
	    params.putString("name", name);
	    params.putString("caption", caption);
	    params.putString("description", description);
	    params.putString("link", pictureLink);
	    params.putString("picture", link);

	    WebDialog feedDialog = (
	        new WebDialog.FeedDialogBuilder(getActivity(),
	            Session.getActiveSession(),
	            params))
	        .setOnCompleteListener(new OnCompleteListener() {          

				@Override
				public void onComplete(Bundle values, FacebookException error) {
					// TODO Auto-generated method stub
					if (error == null) {
	                    // When the story is posted, echo the success
	                    // and the post Id.
	                    final String postId = values.getString("post_id");
	                    if (postId != null) {
	                        Toast.makeText(getActivity(),
	                            "Shared ",
	                            Toast.LENGTH_SHORT).show();
	                        if(fragmentManager != null)
	                        {
	                        	fragmentManager.popBackStack();
	                        }
	                        
	                    } else {
	                        // User clicked the Cancel button
	                        Toast.makeText(getActivity().getApplicationContext(), 
	                            "Publish cancelled", 
	                            Toast.LENGTH_SHORT).show();	                      
	                    }
	                } else if (error instanceof FacebookOperationCanceledException) {
	                    // User clicked the "x" button
	                  
	                } else {
	                    // Generic, ex: network error	                 
	                }
					fragmentManager.popBackStack();
				}

	        })
	        .build();
	    feedDialog.show();
	}
	                                                                                     
}
